import {
  documentDirectory,
  EncodingType,
  getInfoAsync,
  makeDirectoryAsync,
  readAsStringAsync,
  writeAsStringAsync,
  deleteAsync
} from 'expo-file-system/legacy';
import * as Sharing from 'expo-sharing';
// @ts-ignore - xlsx库在React Native中使用
import * as XLSX from 'xlsx';

// 健康数据接口
export interface HealthDataRecord {
  timestamp: string;
  userInfo: {
    id: string | number;
    name: string;
  };
  healthData: {
    heartRate?: number;
    bloodPressureDiastolic?: number;
    bloodPressureSystolic?: number;
    bloodOxygen?: number;
    stressIndex?: number;
    heartAttackIndex?: number;
    reactionTime?: number;
    gripStrength?: number;
    flicker?: number;
    vitalCapacity?: number;
    alcohol?: number;
    healthIndex?: number;
    emotionIndex?: number;
    fatigueIndex?: number;
    overallIndex?: number;
    level?: number;
  };
  date: string;
}

/**
 * 获取当天的日期字符串 (YYYY-MM-DD)
 */
const getTodayDateString = (): string => {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

/**
 * 获取Excel文件名（按日期）
 */
const getExcelFileName = (date: string): string => {
  return `健康测试数据_${date}.xlsx`;
};

/**
 * 获取Excel文件路径
 */
const getExcelFilePath = (date: string): string => {
  const fileName = getExcelFileName(date);
  return `${documentDirectory}excel/${fileName}`;
};

/**
 * 确保Excel目录存在
 */
const ensureExcelDirectory = async (): Promise<void> => {
  const dirPath = `${documentDirectory}excel`;
  const dirInfo = await getInfoAsync(dirPath);
  
  if (!dirInfo.exists) {
    await makeDirectoryAsync(dirPath, { intermediates: true });
  }
};

/**
 * 将健康数据转换为Excel行数据
 */
const convertHealthDataToRow = (record: HealthDataRecord): any[] => {
  const { timestamp, userInfo, healthData } = record;
  
  return [
    timestamp, // 测试时间
    userInfo.name || '未知用户', // 用户姓名
    userInfo.id || '-', // 用户ID
    healthData.heartRate || '-', // 心率
    healthData.bloodPressureSystolic || '-', // 收缩压
    healthData.bloodPressureDiastolic || '-', // 舒张压
    healthData.bloodOxygen || '-', // 血氧
    healthData.stressIndex || '-', // 压力指数
    healthData.heartAttackIndex || '-', // 心康指数
    healthData.reactionTime || '-', // 反应时间
    healthData.gripStrength || '-', // 握力
    healthData.flicker || '-', // 频闪
    healthData.vitalCapacity || '-', // 肺活量
    healthData.alcohol !== null && healthData.alcohol !== undefined ? healthData.alcohol : '-', // 酒精含量
    healthData.healthIndex?.toFixed(2) || '-', // 健康指数
    healthData.emotionIndex?.toFixed(2) || '-', // 情绪指数
    healthData.fatigueIndex?.toFixed(2) || '-', // 疲劳指数
    healthData.overallIndex?.toFixed(2) || '-', // 综合指数
    healthData.level || '-', // 等级
  ];
};

/**
 * 读取现有的Excel文件
 */
const readExistingExcel = async (filePath: string): Promise<any[][]> => {
  try {
    const fileInfo = await getInfoAsync(filePath);
    
    if (!fileInfo.exists) {
      return [];
    }

    // 读取文件内容（Base64编码）
    const base64 = await readAsStringAsync(filePath, {
      encoding: EncodingType.Base64,
    });

    // 将Base64转换为Uint8Array
    const binaryString = atob(base64);
    const buffer = new Uint8Array(binaryString.length);
    for (let i = 0; i < binaryString.length; i++) {
      buffer[i] = binaryString.charCodeAt(i);
    }
    
    // 使用XLSX读取工作簿
    const workbook = XLSX.read(buffer, { type: 'array' });
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];
    
    // 转换为JSON数组
    const data = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: '' });
    return data as any[][];
  } catch (error) {
    console.error('读取Excel文件失败:', error);
    return [];
  }
};

/**
 * 创建新的Excel文件
 */
const createNewExcel = (headers: string[], data: any[][]): Uint8Array => {
  const workbook = XLSX.utils.book_new();
  
  // 准备数据：先添加表头，再添加数据
  const wsData = [headers, ...data];
  const worksheet = XLSX.utils.aoa_to_sheet(wsData);
  
  // 设置列宽
  const colWidths = headers.map((_, index) => {
    if (index === 0) return { wch: 20 }; // 时间戳
    if (index === 1) return { wch: 12 }; // 姓名
    if (index === 2) return { wch: 10 }; // ID
    return { wch: 10 }; // 其他列
  });
  worksheet['!cols'] = colWidths;
  
  // 设置表头样式（如果需要，可以通过xlsx-style实现，但会增加复杂度）
  XLSX.utils.book_append_sheet(workbook, worksheet, '健康测试数据');
  
  // 转换为二进制数据
  const excelBuffer = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' });
  return new Uint8Array(excelBuffer);
};

/**
 * 将Excel数据写入文件
 */
const writeExcelToFile = async (filePath: string, excelData: Uint8Array): Promise<void> => {
  // 将Uint8Array转换为Base64（优化内存使用）
  const chunkSize = 8192; // 8KB chunks
  let binaryString = '';
  
  // 分批处理，避免内存溢出
  for (let i = 0; i < excelData.length; i += chunkSize) {
    const chunk = excelData.slice(i, Math.min(i + chunkSize, excelData.length));
    binaryString += String.fromCharCode.apply(null, Array.from(chunk));
  }
  
  const base64String = btoa(binaryString);
  
  // 写入文件
  await writeAsStringAsync(filePath, base64String, {
    encoding: EncodingType.Base64,
  });
};

/**
 * 添加数据到当天的Excel文件
 * 如果文件不存在则创建，如果存在则追加数据
 */
export const appendDataToDailyExcel = async (record: HealthDataRecord): Promise<string> => {
  try {
    // 确保目录存在
    await ensureExcelDirectory();
    
    // 获取日期和文件路径
    const date = getTodayDateString();
    const filePath = getExcelFilePath(date);
    
    // Excel表头
    const headers = [
      '测试时间',
      '用户姓名',
      '用户ID',
      '心率(bpm)',
      '收缩压(mmHg)',
      '舒张压(mmHg)',
      '血氧(%)',
      '压力指数',
      '心康指数',
      '反应时间(ms)',
      '握力(kg)',
      '频闪',
      '肺活量(ml)',
      '酒精含量',
      '健康指数',
      '情绪指数',
      '疲劳指数',
      '综合指数',
      '等级',
    ];
    
    // 读取现有数据
    let existingData: any[][] = [];
    const fileInfo = await getInfoAsync(filePath);
    
    if (fileInfo.exists) {
      // 文件存在，读取现有数据
      existingData = await readExistingExcel(filePath);
      // 移除表头（如果存在）
      if (existingData.length > 0 && existingData[0][0] === headers[0]) {
        existingData = existingData.slice(1);
      }
    }
    
    // 转换新记录为行数据
    const newRow = convertHealthDataToRow(record);
    
    // 添加新数据
    existingData.push(newRow);
    
    // 创建Excel文件
    const excelData = createNewExcel(headers, existingData);
    
    // 写入文件
    await writeExcelToFile(filePath, excelData);
    
    // 打印文件路径信息（方便调试和用户查看）
    console.log('=== Excel文件保存信息 ===');
    console.log(`文件路径: ${filePath}`);
    console.log(`文件名: ${getExcelFileName(date)}`);
    console.log(`记录数: ${existingData.length}`);
    console.log(`Android文件位置: /data/data/com.anonymous.AstraSafe/files/excel/${getExcelFileName(date)}`);
    console.log('提示: 使用"分享文件"功能可导出到Downloads文件夹');
    console.log('======================');
    
    return filePath;
  } catch (error) {
    console.error('添加数据到Excel文件失败:', error);
    throw error;
  }
};

/**
 * 获取文件保存路径信息（用于显示给用户）
 */
export const getFileInfo = async (date?: string): Promise<{ path: string; fileName: string; exists: boolean; androidPath: string }> => {
  const targetDate = date || getTodayDateString();
  const filePath = getExcelFilePath(targetDate);
  const fileName = getExcelFileName(targetDate);
  const fileInfo = await getInfoAsync(filePath);
  
  // Android设备上的实际路径（仅用于显示）
  const androidPath = `/data/data/com.anonymous.AstraSafe/files/excel/${fileName}`;
  
  return {
    path: filePath,
    fileName,
    exists: fileInfo.exists,
    androidPath,
  };
};

/**
 * 获取当天Excel文件的路径
 */
export const getTodayExcelFilePath = (): string => {
  const date = getTodayDateString();
  return getExcelFilePath(date);
};

/**
 * 检查当天的Excel文件是否存在
 */
export const checkTodayExcelExists = async (): Promise<boolean> => {
  const filePath = getTodayExcelFilePath();
  const fileInfo = await getInfoAsync(filePath);
  return fileInfo.exists;
};

/**
 * 分享/导出Excel文件（可选功能）
 */
export const shareExcelFile = async (date?: string): Promise<void> => {
  try {
    const targetDate = date || getTodayDateString();
    const filePath = getExcelFilePath(targetDate);
    
    const fileInfo = await getInfoAsync(filePath);
    if (!fileInfo.exists) {
      throw new Error('Excel文件不存在');
    }
    
    const canShare = await Sharing.isAvailableAsync();
    if (canShare) {
      await Sharing.shareAsync(filePath);
    } else {
      console.log('当前平台不支持分享功能');
    }
  } catch (error) {
    console.error('分享Excel文件失败:', error);
    throw error;
  }
};

/**
 * Excel文件信息接口
 */
export interface ExcelFileInfo {
  fileName: string;
  filePath: string;
  date: string;
  exists: boolean;
  size?: number;
  modificationTime?: number;
}

/**
 * 获取所有Excel文件列表
 */
export const getAllExcelFiles = async (): Promise<ExcelFileInfo[]> => {
  try {
    // 确保Excel目录存在
    await ensureExcelDirectory();
    
    const excelDir = `${documentDirectory}excel`;
    const dirInfo = await getInfoAsync(excelDir);
    
    if (!dirInfo.exists) {
      return [];
    }
    
    // 获取目录中的所有文件
    const files: ExcelFileInfo[] = [];
    
    // 由于React Native的文件系统API限制，我们需要使用已知模式来查找文件
    // 这里我们检查最近30天的文件
    const today = new Date();
    const fileInfos: ExcelFileInfo[] = [];
    
    for (let i = 0; i < 30; i++) {
      const date = new Date(today);
      date.setDate(date.getDate() - i);
      
      const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      const fileName = getExcelFileName(dateStr);
      const filePath = getExcelFilePath(dateStr);
      
      try {
        const fileInfo = await getInfoAsync(filePath);
        
        if (fileInfo.exists) {
          fileInfos.push({
            fileName,
            filePath,
            date: dateStr,
            exists: true,
            size: fileInfo.size || 0,
            modificationTime: fileInfo.modificationTime || 0
          });
        }
      } catch (error) {
        // 忽略单个文件的错误
        console.warn(`检查文件失败: ${filePath}`, error);
      }
    }
    
    // 按修改时间排序（最新的在前）
    fileInfos.sort((a, b) => (b.modificationTime || 0) - (a.modificationTime || 0));
    
    return fileInfos;
  } catch (error) {
    console.error('获取Excel文件列表失败:', error);
    return [];
  }
};

/**
 * 删除指定日期的Excel文件
 */
export const deleteExcelFile = async (date: string): Promise<boolean> => {
  try {
    const filePath = getExcelFilePath(date);
    const fileInfo = await getInfoAsync(filePath);
    
    if (!fileInfo.exists) {
      throw new Error('文件不存在');
    }
    
    await deleteAsync(filePath);
    console.log(`已删除Excel文件: ${filePath}`);
    return true;
  } catch (error) {
    console.error(`删除Excel文件失败 (${date}):`, error);
    return false;
  }
};

/**
 * 删除所有Excel文件
 */
export const deleteAllExcelFiles = async (): Promise<{ success: number; failed: number }> => {
  try {
    const files = await getAllExcelFiles();
    let successCount = 0;
    let failedCount = 0;
    
    for (const file of files) {
      const result = await deleteExcelFile(file.date);
      if (result) {
        successCount++;
      } else {
        failedCount++;
      }
    }
    
    console.log(`删除完成: 成功 ${successCount} 个，失败 ${failedCount} 个`);
    return { success: successCount, failed: failedCount };
  } catch (error) {
    console.error('删除所有Excel文件失败:', error);
    return { success: 0, failed: 0 };
  }
};

/**
 * 创建示例Excel文件（用于测试）
 */
export const createSampleExcelFile = async (): Promise<string> => {
  try {
    // 创建示例健康数据
    const sampleData: HealthDataRecord = {
      timestamp: new Date().toLocaleString('zh-CN'),
      userInfo: {
        id: 'test001',
        name: '测试用户'
      },
      healthData: {
        heartRate: 75,
        bloodPressureDiastolic: 80,
        bloodPressureSystolic: 120,
        bloodOxygen: 98,
        stressIndex: 45,
        heartAttackIndex: 10,
        reactionTime: 350,
        gripStrength: 35,
        flicker: 30,
        vitalCapacity: 3500,
        alcohol: 0,
        healthIndex: 85,
        emotionIndex: 75,
        fatigueIndex: 70,
        overallIndex: 77,
        level: 2
      },
      date: new Date().toLocaleDateString('zh-CN')
    };
    
    // 保存到Excel文件
    const filePath = await appendDataToDailyExcel(sampleData);
    console.log('示例Excel文件已创建:', filePath);
    
    return filePath;
  } catch (error) {
    console.error('创建示例Excel文件失败:', error);
    throw error;
  }
};

